#include "ThreadPool.h"

ThreadPool::ThreadPool(size_t threadNum, size_t queueSize, ConnectionPool* connPool)
    : _threadNum(threadNum), _queueSize(queueSize), _isExit(false), _taskQueue(queueSize), _connPool(connPool)
{
}

void ThreadPool::start()
{
    for (size_t i = 0; i < _threadNum; ++i)
    {
        _threads.emplace_back(thread(&ThreadPool::doTask, this)); // 创建多个线程
    }
}

void ThreadPool::stop()
{
    //队列中任务全部执行完
    while (!_taskQueue.empty())
    {
        std::this_thread::sleep_for(std::chrono::milliseconds(100));
    }
    _isExit = true;
    _taskQueue.wakeup(); // 唤醒所有线程
    for (auto &thread : _threads)
    {
        thread.join();
    }
}

void ThreadPool::addTask(Task &&taskcb)
{
    _taskQueue.push(std::move(taskcb));
}

Task ThreadPool::getTask()
{
    return _taskQueue.pop();
}

void ThreadPool::doTask()
{
    while (!_isExit)
    {
        Task taskcb = getTask();
        if (taskcb)
            taskcb();
        else
        {
            std::this_thread::yield(); // 让出cpu
        }
    }
}

shared_ptr<MySQLConnection> ThreadPool::getConnection()
{
    return _connPool->getConnection(); // 从连接池获取连接

} 

void ThreadPool::releaseConnection(shared_ptr<MySQLConnection> &conn)
{
    _connPool->releaseConnection(conn); // 释放连接
}